import React, { useEffect, useState,FC } from 'react';
import '../assets/css/Userinfo.css'
import {Form, Input, Cascader, Select, Button, Space, Table, Modal, message,Pagination } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {getUserList,getUserDel,getUserDelall,getUsetUpdata,getUserType} from '../apis/userinfo'
import {getBuildingList} from '../apis/building'
import {baceUrl} from '../utils/config'
import { ExclamationCircleOutlined } from '@ant-design/icons';
import UserInfoAdd from "../components/userInfo/UserInfoAdd";

const Userinfo:FC =()=> {
    const [form] = Form.useForm();
    const [, forceUpdate] = useState({});

//表单查询
    //楼栋id
    const [options,setOptions]: any =useState([]);
    //楼栋列表
    const getBuildinglist = async ()=>{
        const res:any = await getBuildingList({}).catch()
        if(res&&res.errCode===10000){
            setOptions(res.data.list)
        }
    }
    //居民类型
    const [selectList,getSelectList] = useState([])
    const getTypeList = async ()=>{
        const res:any = await getUserType({}).catch()
        if(res&&res.errCode===10000){
            getSelectList(res.data.list)
        }
    }
    const onFinish = (values: any) => {
        if(values.buildingid){
            setParams({...values, buildingid: values.buildingid[values.buildingid.length-1]})
        }else{
            setParams(values)
        }
    };
//表格
    //表格数据
    const [data,setDataList]: any= useState([]);
    const [params,setParams]:any = useState({
        page:1,
        psize:10,
        name:'',
        mobile:'',
        houseno:'',
        state:null,
        usertype:'',
        buildingid:null,
    })
    const [loading,setLoading] = useState(true)
    const getDatalist = async ()=>{
        const res:any = await getUserList(params)
        if(res.errCode===10000){
            setLoading(false)
            setDataList(res.data.list)
            setTotal(res.data.counts)
        }
    }
    //分页
    const [total,setTotal] = useState(0)
    const changePagination = (page:any,pSize:any)=>{
        setParams({...params, page, psize: pSize})
    }
    //多选
    const rowSelection = {
        onChange: (selectedRowKeys:any, selectedRows:any) => {
            setSelection(selectedRowKeys)
        },
        getCheckboxProps: (record:any) => ({
            disabled: record.name === 'Disabled User', // Column configuration not to be checked
            name: record.name,
        }),
    };
    const [selectionType, ] = useState<'checkbox' | 'radio'>('checkbox');
    const [selection,setSelection] = useState([])
    //删除
    const getDataDel:any = (key:number,id?:number)=>{
        return  ()=>{
            Modal.confirm({
                title: '提示',
                icon: <ExclamationCircleOutlined />,
                content: '确定要永久删除数据吗？',
                okText: '确认',
                cancelText: '取消',
                onOk:async()=>{
                    const res:any = key===1?await getUserDel({id:id}):await getUserDelall({ids:selection})
                    if(res.errCode===10000){
                        getDatalist()
                        message.success('删除成功', 10);
                    }else{
                        message.error(res.errMsg, 10);
                    }
                }
            });
        }
    }
    //审核
    const getDataUpdata = ()=>{
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: '确定要审核吗？',
            okText: '确认',
            cancelText: '取消',
            onOk:async()=>{
                const res:any = await getUsetUpdata({ids:selection,state:2}).catch(()=>{})
                if(res&&res.errCode===10000){
                    message.success(res.errMsg, 10);
                    getDatalist()
                }else{
                    message.error(res.errMsg, 10);
                }
            }
        });

    }
    //添加
    const [addShow,getAddShow] = useState(false)
    const [listData,setListData] = useState({})
    const getUserAdd=(val?:any)=>{
        return ()=>{
            setListData(val)
            getAddShow(true)
        }
    }
    const getUserClose = ()=>{
        getAddShow(false)
        getDatalist()
    }
    //数据
    const columns: ColumnsType<any> = [
        {
            title: 'id',
            dataIndex: 'id',
            align:'center',
        },
        {
            title: '头像',
            dataIndex: 'photo',
            align:'center',
            render:(_,record)=>(
                <Space size="middle">
                    <img className={record.photo?'imgUrl':'imgUrlHide'} src={baceUrl+record.photo} />
                </Space>
            )
        },
        {
            title: '姓名',
            dataIndex: 'name',
            align:'center',
        },
        {
            title: '业主类型',
            dataIndex: 'usertypeName',
            align:'center',
        },
        {
            title: '性别',
            dataIndex: 'sex',
            align:'center',
            render:(_,record)=>(
                <div>
                    {record.sex===0?'女':'男'}
                </div>
            )
        },
        {
            title: '身份证号',
            dataIndex: 'cardid',
            align:'center',
        },
        {
            title: '手机号',
            dataIndex: 'mobile',
            align:'center',
        },
        {
            title: '籍贯',
            dataIndex: 'usernative',
            align:'center',
        },
        {
            title: '民族',
            dataIndex: 'nation',
            align:'center',
        },
        {
            title: '小区',
            dataIndex: 'building',
            align:'center',
            width:200,
        },
        {
            title: '房间号',
            dataIndex: 'houseno',
            align:'center',
            width:120,
        },
        {
            title: '审核状态',
            dataIndex: 'state',
            align:'center',
            render:(_,record)=>(
                <div>
                    {record.state===1?'未审核':'已审核'}
                </div>
            )
        },
        {
            title: '操作',
            align:'center',
            render: (_, record) => (
                <Space size="middle">
                    <div className="funBtn examine" onClick={getUserAdd(record)}>修改</div>
                    <div className="funBtn del" onClick={getDataDel(1,record.id)}>删除</div>
                </Space>
            ),
        },
    ];
    useEffect(() => {
        forceUpdate({});
        getDatalist()
        getBuildinglist()
        getTypeList()
    }, [params]);
    return (
        <div className="userinfo">
            <div className="header">
                <span className="title">居民管理</span>
            </div>
            <div className="centnet">
                {/*  表单  */}
                <Form form={form} name="horizontal_login" layout="inline" onFinish={onFinish}>
                    <Form.Item label="楼栋ID" name="buildingid" >
                        <Cascader
                            style={{width: '200px'}}
                            changeOnSelect
                            fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                            options={options}
                            expandTrigger="hover"
                            placeholder="请选择"
                        />
                    </Form.Item>
                    <Form.Item label="姓名" name="name">
                        <Input allowClear placeholder="居民姓名"/>
                    </Form.Item>
                    <Form.Item label="电话" name="mobile">
                        <Input allowClear maxLength={11} placeholder="居民电话" />
                    </Form.Item>
                    <Form.Item label="房间号" name="houseno">
                        <Input allowClear placeholder="房间号" />
                    </Form.Item>
                    <Form.Item label="用户类型" name="usertype">
                        <Select
                            placeholder="请选择"
                            allowClear
                            optionFilterProp="children"
                            fieldNames={{label: 'name',value:'id'}}
                            options={selectList}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button htmlType="submit" type="primary">查询</Button>
                    </Form.Item>
                </Form>
                {/*  按钮  */}
                <div className="btnBox">
                    <div className="funBtn" onClick={getUserAdd({id:0})}>添加</div>
                    <div className="funBtn del" onClick={getDataDel(2)}>批量删除</div>
                    <div className="funBtn examine" onClick={getDataUpdata}>批量审核</div>
                </div>
                {/*  表格  */}
                <Table
                    className="tableBox"
                    bordered
                    loading={loading}
                    columns={columns}
                    dataSource={data}
                    pagination={false}
                    rowKey={record => record.id}
                    rowSelection={{
                        type: selectionType,
                        ...rowSelection,
                    }}
                />
                <Pagination
                    className="Pagination"
                    total={total}
                    current={params.page}
                    defaultCurrent={params.page}
                    defaultPageSize={params.psize}
                    showSizeChanger
                    showQuickJumper
                    pageSizeOptions={[5,10,20,40]}
                    onChange={changePagination}
                    showTotal={total => `共${total}条`}
                />
            </div>
            {
                addShow &&
                <UserInfoAdd
                    addShow={addShow}
                    listData={listData}
                    getUserClose={getUserClose}
                ></UserInfoAdd>
            }
        </div>
    );
}

export default Userinfo;
